<template>
  <BasicModal v-bind="$attrs" @register="register" :title="displayModuleTitle" @ok="onButtonOk">
    <BasicForm @register="registerForm" />
    <a-upload-dragger
      :file-list="fileList"
      name="file"
      :maxCount="1"
      accept=".xlsx,.xls"
      @change="handleChange"
      :beforeUpload="false"
      :customRequest="
        () => {
          return;
        }
      "
      @remove="removeFile"
    >
      <p class="ant-upload-drag-icon">
        <CloudUploadOutlined />
      </p>
      <p class="ant-upload-hint"> 请点击或拖拽上传excel文件 </p>
    </a-upload-dragger>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref, toRaw } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { CloudUploadOutlined } from '@ant-design/icons-vue';
  import * as XLSX from 'xlsx';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { facilityImportSchema } from './facility.data';
  import { importFacility } from '/@/api/ehs/facility';
  export default defineComponent({
    components: { BasicModal, CloudUploadOutlined, BasicForm },
    emits: ['success'],
    props: ['unitOption'],
    name: 'ImportFacilityModal',
    setup(props, { emit }) {
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const orgcode = ref();
      const title = ref([]);
      const tableData = ref([]);
      const fileList = ref([]);
      const fileData = ref({});
      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 120,
        schemas: facilityImportSchema,
        showActionButtonGroup: false,
        scrollToFirstError: true,
        actionColOptions: {
          span: 24,
        },
      });
      const [register, { setModalProps, closeModal }] = useModalInner((data) => {
        resetFields();
        title.value = [];
        tableData.value = [];
        fileList.value = [];
        fileData.value = {};
        updateSchema({
          field: 'unitid',
          componentProps: {
            getPopupContainer: (triggerNode) => document.body,
            treeData: props.unitOption,
            fieldNames: { label: 'unitname', value: 'unitid', children: 'children' },
            listHeight: 150,
            treeDefaultExpandAll: true, //默认展开
            showCheckedStrategy: 'SHOW_ALL', //定义选中项回填的方式:默认只显示子节点;SHOW_ALL:显示所有选中节点(包括父节点);SHOW_PARENT:只显示父节点(当父节点下所有子节点都选中时).
          },
        });
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.orgcode) {
            orgcode.value = unrefData.orgcode;
          }
        }
      });

      function readFile(file) {
        return new Promise((resolve) => {
          let reader = new FileReader();
          reader.readAsBinaryString(file);
          reader.onload = (ev) => {
            resolve(ev.target.result);
          };
        });
      }

      function handleChange(info) {
        const fileType = info.file.name.split('.').pop();
        if (fileType === 'xlsx' || fileType === 'xls') {
          fileData.value = info.file.originFileObj; // 获取原始文件
          fileList.value = info.fileList;
          info.file.status = 'done'; //更改文件状态
        } else if (fileType !== 'xlsx' || fileType !== 'xls') {
          createMessage.error('文件格式不符,请上传excel格式文件');
        }
      }
      function removeFile() {
        fileList.value = [];
        fileData.value = {};
      }

      async function onButtonOk() {
        setModalProps({ confirmLoading: true });
        tableData.value = [];
        const importObj = await validate();
        // console.log(fileData.value, 'fileData');
        if (Object.keys(fileData.value).length < 1)
          return createMessage.error('无有效excel上传文件,请确认后重试');
        // 将file变成二进制读取到的
        let data = await readFile(fileData.value);
        // 将得到的二进制转化一下
        let workbook = XLSX.read(data, { type: 'binary' });
        // 最后把数据转成json格式的
        let worksheet = workbook.Sheets[workbook.SheetNames[0]]; //这里是表格的名字,这里取第一个表格,1就是第二个表格数据
        //将得到的worksheet转化为json格式
        data = XLSX.utils.sheet_to_json(worksheet, { header: 1 }).slice(importObj.startRow - 1);
        console.log('data', data);

        // 这个是表格所有的标题
        title.value = Object.keys(data[0]);
        data.forEach((item, index) => {
          let obj = {
            orgcode: orgcode.value,
            unitid: importObj.unitid,
            code: item[importObj.code - 1],
            name: item[importObj.name - 1],
            cat1: item[importObj.cat1 - 1],
            cat2: item[importObj.cat2 - 1],
            status: item[importObj.status - 1] == '在用' ? 1 : 0,
          };
          tableData.value.push(obj);
        });
        console.log('tableData.value', tableData.value);
        importFacility(toRaw(tableData.value)).then((res) => {
          if (!res) {
            closeModal();
            emit('success');
            createMessage.success('导入成功');
          } else createMessage.error('导入失败');
          setModalProps({ confirmLoading: false });
        });
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });
      return {
        register,
        fileList,
        fileData,
        closeModal,
        displayModuleTitle,
        handleChange,
        removeFile,
        onButtonOk,
        registerForm,
      };
    },
  });
</script>
